#!/usr/bin/env python3
"""
Text2SQL评估系统完整启动脚本
同时启动后端和前端服务
"""
import os
import sys
import subprocess
import threading
import time
import signal

def check_requirements():
    """检查环境要求"""
    print("🔍 检查环境要求...")
    
    # 检查Python
    python_version = sys.version_info
    if python_version.major < 3 or (python_version.major == 3 and python_version.minor < 8):
        print("✗ Python版本过低，需要Python 3.8+")
        return False
    print(f"✓ Python版本: {python_version.major}.{python_version.minor}.{python_version.micro}")
    
    # 检查Node.js
    try:
        result = subprocess.run(['node', '--version'], capture_output=True, text=True)
        if result.returncode == 0:
            print(f"✓ Node.js版本: {result.stdout.strip()}")
        else:
            print("✗ Node.js未安装")
            return False
    except FileNotFoundError:
        print("✗ Node.js未安装")
        return False
    
    # 检查环境变量文件
    if not os.path.exists('backend/.env'):
        print("⚠ 未找到 backend/.env 文件")
        print("请创建 backend/.env 文件并设置 OPENAI_API_KEY")
        print("参考 backend/env_example.txt 文件")
        return False
    
    return True

def install_backend_deps():
    """安装后端依赖"""
    print("📦 安装后端依赖...")
    try:
        result = subprocess.run([sys.executable, '-m', 'pip', 'install', '-r', 'backend/requirements.txt'], 
                              check=True, capture_output=True, text=True)
        print("✓ 后端依赖安装完成")
        return True
    except subprocess.CalledProcessError as e:
        print(f"✗ 后端依赖安装失败: {e}")
        return False

def install_frontend_deps():
    """安装前端依赖"""
    print("📦 安装前端依赖...")
    try:
        result = subprocess.run(['npm', 'install'], cwd='frontend', check=True, 
                              capture_output=True, text=True)
        print("✓ 前端依赖安装完成")
        return True
    except subprocess.CalledProcessError as e:
        print(f"✗ 前端依赖安装失败: {e}")
        return False

def start_backend():
    """启动后端服务"""
    print("🔧 启动后端服务...")
    try:
        subprocess.run([sys.executable, 'app.py'], cwd='backend')
    except KeyboardInterrupt:
        print("\n后端服务已停止")
    except Exception as e:
        print(f"✗ 后端启动失败: {e}")

def start_frontend():
    """启动前端服务"""
    print("🌐 启动前端服务...")
    try:
        subprocess.run(['npm', 'run', 'serve'], cwd='frontend')
    except KeyboardInterrupt:
        print("\n前端服务已停止")
    except Exception as e:
        print(f"✗ 前端启动失败: {e}")

def signal_handler(sig, frame):
    """信号处理器"""
    print("\n\n🛑 正在停止所有服务...")
    sys.exit(0)

def main():
    """主函数"""
    print("=== Text2SQL评估系统完整启动 ===")
    
    # 注册信号处理器
    signal.signal(signal.SIGINT, signal_handler)
    signal.signal(signal.SIGTERM, signal_handler)
    
    # 检查环境要求
    if not check_requirements():
        print("\n❌ 环境检查失败，请解决上述问题后重试")
        return
    
    # 安装依赖
    print("\n📦 安装项目依赖...")
    if not install_backend_deps():
        print("❌ 后端依赖安装失败")
        return
    
    if not install_frontend_deps():
        print("❌ 前端依赖安装失败")
        return
    
    print("\n🚀 启动服务...")
    print("🔧 后端服务: http://localhost:5000")
    print("🌐 前端服务: http://localhost:8080")
    print("⏹️  按 Ctrl+C 停止所有服务")
    print("-" * 60)
    
    # 启动后端服务（在后台线程中）
    backend_thread = threading.Thread(target=start_backend, daemon=True)
    backend_thread.start()
    
    # 等待后端启动
    print("⏳ 等待后端服务启动...")
    time.sleep(3)
    
    # 启动前端服务
    try:
        start_frontend()
    except KeyboardInterrupt:
        print("\n👋 所有服务已停止")

if __name__ == "__main__":
    main()
